/* File Info 
 * Author:      cknight 
 * CreateTime:  2021/1/20 下午1:18:52 
 * LastEditor:  cknight 
 * ModifyTime:  2021/1/25 下午1:21:51 
 * Description: 获取数据的接口
 */
const superagent = require("../config/superagent");
const cheerio = require("cheerio");
const request = require("request");
const axios = require("axios")
const ONE = "http://wufazhuce.com/"; // ONE的web版网站
const POISON = "https://8zt.cc/"; //毒鸡汤网站
const TXHOST = "https://api.tianapi.com/txapi/"; // 天行host 官网：tianapi.com
const DJAPI = 'https://api.djapi.cn/joke/get'
const { APIKEY, TIANQIAPI, TULINGURL, TULINGKEY, DJAPIKEY } = require("../config") // 天行key，请先去网站注册填写key  注册免费  注册后申请下面的接口即可。
const path = require('path'); //系统路径模块
const fs = require('fs'); //文件模块
/* 
 * @Description: 获取天气
 */
async function getWeather(location) {

    try {
        let res = await superagent.req('https://tianqiapi.com/api', "GET", {
            appid: TIANQIAPI.id,
            appsecret: TIANQIAPI.APPSecret,
            version: 'v6',
            city: location
        });
        let content = JSON.parse(res.text);
        if (content) {
            return content
        } else {
            console.log("获取接口失败", content.msg);
        }
    } catch (err) {
        console.log("获取接口失败", err);
        return err;
    }
}

/**
 * 图灵接口返回图片搜索链接抓取图片
 */
async function getTulingImg(url) {
    try {
        // let res = await axios.get(`https://m.image.so.com/j?q=${url}&pn=30&sn=5&kn=0&gn=0&cn=0`)
        let { data } = await axios.get(`https://m.image.so.com/v1/windowAds?q=${url}`)
        return data ? data.data ? data.data.second_jump_ads ? data.data.second_jump_ads.guess[0].sites : [] : [] : []
    } catch (err) {
        console.log("错误", err);
        return err;
    }
}
/**
 * 获取每日一句
 */
async function getOne() {
    try {
        let res = await superagent.req(ONE, "GET");
        let $ = cheerio.load(res.text);
        let todayOneList = $("#carousel-one .carousel-inner .item");
        let todayOne = $(todayOneList[0])
            .find(".fp-one-cita")
            .text()
            .replace(/(^\s*)|(\s*$)/g, "");
        let todayOnePic = $(todayOneList[0])
            .find(".fp-one-imagen")
            .attr("src")
            .replace(/(^\s*)|(\s*$)/g, "");
        return { word: todayOne, pic: todayOnePic };
    } catch (err) {
        console.log("错误", err);
        return err;
    }
}
/* 
 * @Description: 一篇好文
 */
async function getOneAritcle() {
    try {
        let res = await superagent.req(ONE, "GET");
        let $ = cheerio.load(res.text);
        let todayOne = $(".fp-one-articulo .corriente .one-articulo-titulo a")
            .attr('href')
            .replace(/(^\s*)|(\s*$)/g, "");
        try {
            let res = await superagent.req(todayOne, "GET");
            let $ = cheerio.load(res.text);
            let todayArt = {}
            todayArt.quote = $('.one-articulo .comilla-cerrar').text();
            todayArt.title = $('.one-articulo .articulo-titulo').text();
            todayArt.author = $('.one-articulo .articulo-autor').text();
            todayArt.content = $('.one-articulo .articulo-contenido').text().replace(/(^\s*)|(\s*$)|(\&nbsp\;)/g, "")
            return todayArt
        } catch (err) {
            console.log("错误", err);
            return err;
        }
    } catch (err) {
        console.log("错误", err);
        return err;
    }
}
/* 
 * @Description: 土味情话
 */
async function getLoveSay() {
    const url = TXHOST + "saylove/index";
    try {
        let res = await superagent.req(url, "GET", {
            key: APIKEY
        });
        let content = JSON.parse(res.text);
        if (content.code === 200) {
            return content.newslist[0];
        } else {
            console.log("获取接口失败", content.msg);
        }
    } catch (err) {
        console.log("获取接口失败", err);
    }
}
/* 
 * @Description: 来句诗词
 */
async function getPoerty() {
    const url = 'https://v2.jinrishici.com/sentence';
    try {
        let res = await superagent.req(url, "GET", {
            "X-User-Token": "FWdeblDq89FpJMlDv4TxpspuKg0IkZR1"
        });
        let content = JSON.parse(res.text);
        if (content) {
            return content.data
        } else {
            console.log("获取接口失败");
        }
    } catch (err) {
        console.log("获取接口失败", err);
    }
}
/* 
 * @Description: 心灵鸡汤
 */
async function getHeartSoup() {
    const url = 'https://v1.hitokoto.cn/';
    try {
        let res = await superagent.req(url, "GET");
        let content = JSON.parse(res.text);
        if (content) {
            return content
        } else {
            console.log("获取接口失败");
        }
    } catch (err) {
        console.log("获取接口失败", err);
    }
}
/* 
 * @Description: 舔狗日记
 */
async function getNoHouse() {
    const url = TXHOST + "tiangou/index";
    try {
        let res = await superagent.req(url, "GET", {
            key: APIKEY
        });
        let content = JSON.parse(res.text);
        if (content.code === 200) {
            return content.newslist[0];
        } else {
            console.log("获取接口失败", content.msg);
        }
    } catch (err) {
        console.log("获取接口失败", err);
    }
}

/**
 * 获取每日毒鸡汤
 */
async function getSoup() {
    try {
        let res = await superagent.req(POISON, "GET");
        let $ = cheerio.load(res.text);
        const content = $("#sentence").text();
        return content;
    } catch (err) {
        console.error("err");
        return err;
    }
}

/**
 * 获取全国肺炎数据
 */
function getChinaFeiyan() {
    return new Promise((resolve, reject) => {
        request.get({
                url: `https://c.m.163.com/ug/api/wuhan/app/data/list-total?t=${new Date().getTime()}`
            },
            function(err, response) {
                if (err) {
                    reject(err);
                }
                const res = JSON.parse(response.body);
                resolve(res);
            }
        );
    });
}
/**
 * 获取省份肺炎数据
 */
async function getProvinceFeiyan(name) {
    return new Promise((resolve, reject) => {
        request.get({
                url: `https://gwpre.sina.cn/interface/fymap2020_data.json?t=${new Date().getTime()}`
            },
            function(err, response) {
                if (err) {
                    reject(err);
                }
                try {
                    const res = JSON.parse(response.body);
                    res.data.list.forEach(item => {
                        if (name === item.name) {
                            resolve(item);
                            return;
                        }
                    });
                } catch (error) {
                    reject(err);
                }
            }
        );
    });
}
/**
 * 获取神回复
 */
async function getGodReply() {
    const url = TXHOST + "godreply/index";
    try {
        let res = await superagent.req(url, "GET", {
            key: APIKEY
        });
        let content = JSON.parse(res.text);
        if (content.code === 200) {
            return content.newslist[0];
        } else {
            console.log("获取接口失败", content.msg);
        }
    } catch (err) {
        console.log("获取接口失败", err);
    }
}
/**
 * 每日英语一句话
 */
async function getEnglishOne() {
    const url = TXHOST + "ensentence/index";
    try {
        let res = await superagent.req(url, "GET", {
            key: APIKEY
        });
        let content = JSON.parse(res.text);
        if (content.code === 200) {
            return content.newslist[0]; //en英文  zh中文
        } else {
            console.log("获取接口失败", content.msg);
        }
    } catch (err) {
        console.log("获取接口失败", err);
    }
}
// 图灵接口
async function tuling(msg, userId) {
    let data = {
        "reqType": 0, //0 文本 1 图片 2 音频
        "perception": {
            "inputText": { "text": msg },
        }, //输入信息
        "userInfo": {
            "apiKey": TULINGKEY,
            "userId": userId
        }
    }
    let res = await axios.post(TULINGURL, data)
    return res.data
}
// 处理成语接龙 https://yuansasi-1253312316.cos.ap-chengdu.myqcloud.com/idiom.json
async function chengyujielong(msg) {
    var file = path.join(__dirname, 'data/idiom.json'); //文件路径，__dirname为当前运行js文件的目录
    let json = ''
    var dict = {}
    await fs.readFile(file, 'utf-8', function(err, data) {
        if (err) {
            console.log('文件读取失败');
        } else {
            json = JSON.parse(data)
        }
    });
    if (json) {
        for (let item of json) {
            var word = item["word"].replace("，", "").replace(" ", "");
            dict[word] = {
                word,
                pinyin: item["pinyin"].split(" "),
                explanation: item["explanation"],
            };
        }
    }
}
/**
 * 获取笑话大全
 */
async function getJoke() {
    try {
        let res = await superagent.req(DJAPI, "GET", {
            cn_to_unicode: 1,
            limit: 1,
            token: DJAPIKEY,
            datatype: 'json',
            methods: 'get',
            _: Date.now(),
        });
        let { ErrorCode, Result } = JSON.parse(res);
        if (ErrorCode === 0) {
            return Result.content
        } else {
            console.log("获取接口失败", content.msg);
        }
    } catch (err) {
        console.log("获取接口失败", err);
    }
}
module.exports = {
    getOne,
    getSoup,
    getChinaFeiyan,
    getProvinceFeiyan,
    getGodReply,
    getEnglishOne,
    getNoHouse,
    getHeartSoup,
    getPoerty,
    getOneAritcle,
    getWeather,
    tuling,
    getTulingImg,
    getLoveSay,
    chengyujielong,
    getJoke
};